package cn.tedu.tmall.admin.mall.handler;

import cn.tedu.tmall.common.exception.ServiceException;
import cn.tedu.tmall.common.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理运行时异常
     * @param e 运行时异常
     * @return JsonResult
     */
    @ExceptionHandler
    public JsonResult handleRuntimeException(ServiceException e){
        log.error("捕获ServiceException:{}",e.getMessage());
        return JsonResult.fail(e.getMessage());
    }

    /**
     * 处理多条异常
     */
    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        //接收多个异常
        List<FieldError> errors = e.getFieldErrors();
        //连接成字符串
        StringBuilder allMessage = new StringBuilder();
        for (FieldError error : errors) {
            allMessage.append(error.getDefaultMessage()).append("|");
        }
        //去除最后的分隔符
        String str = allMessage.delete(allMessage.lastIndexOf("|"), allMessage.length()).toString();
        log.error("捕获数据校验异常:{}",str);
        return JsonResult.fail(str);
    }

//    @ExceptionHandler
    public JsonResult handleBeanPropertyBindingResult(BeanPropertyBindingResult e){
        log.error("捕获BeanPropertyBindingResult",e);
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuffer message = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            message.append(fieldError.getDefaultMessage());
        }
        return JsonResult.fail(message.toString());
    }

    /**
     * 兜底策略
     * 处理其他异常Throwable
     */
    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e){
        log.error("捕获Throwable:{}",e.getMessage());
        String msg = "网络异常，请重试";
        return JsonResult.fail(msg);
    }
}
